#!/usr/bin/env node
// chmod +x scripts/generate-latest-changelog-date.js

import { parseISO } from "date-fns";
import { promises as fs } from "node:fs";
import path from "node:path";

const changelogDir = path.join(process.cwd(), "src/changelogs");
const filenames = await fs.readdir(changelogDir);

let latestChangelogDate = new Date(0);

for (const file of filenames) {
  const filenameWithoutExtension = file.replace(/\.mdx$/, "");
  const isoDate = parseISO(filenameWithoutExtension);
  if (isoDate > latestChangelogDate) {
    latestChangelogDate = isoDate;
  }
}

// Define the output path for the last-changelog-date.ts file
const outputPath = path.join(
  process.cwd(),
  "src/changelogs/last-changelog-date.ts",
);

// Prepare the content to be written to the file
const content = `// This file is generated by the generate-latest-changelog-date script
export const lastChangelogDate = new Date("${latestChangelogDate.toISOString()}");\n`;

// Write the content to the last-changelog-date.ts file
await fs.writeFile(outputPath, content);

console.log(`Last changelog date exported to ${outputPath}`);
